package third.lib.zfb.outpay.bcredpacket;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayFundTransUniTransferRequest;
import com.alipay.api.response.AlipayFundTransUniTransferResponse;
import java.math.BigDecimal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import third.lib.common.exception.ThirdException;
import third.lib.common.logger.ThirdLogger;
import third.lib.common.status.ThirdStatus;
import third.lib.zfb.common.config.ZfbAppConfig;
import third.lib.zfb.common.model.PayInfo;
import third.lib.zfb.common.utils.ZfbUtils;
import third.lib.zfb.outpay.bcredpacket.model.BcRedPacketBizContent;

@Service
public class ZfbBcRedPacket {
    @Autowired
    ThirdLogger thirdLogger;
    @Autowired
    ZfbAppConfig config;

    public ZfbBcRedPacket() {
    }

    public void sendBcRedPacket(String bizNo, BigDecimal amount, String title, String userId, String name) throws ThirdException {
        BcRedPacketBizContent content = new BcRedPacketBizContent();
        content.setOut_biz_no(bizNo);
        content.setTrans_amount(amount);
        content.setOrder_title(title);
        content.setProduct_code("TRANS_ACCOUNT_NO_PWD");
        PayInfo payInfo = new PayInfo();
        payInfo.setIdentity_type("ALIPAY_USER_ID");
        payInfo.setIdentity(userId);
        content.setPayee_info(payInfo);

        AlipayFundTransUniTransferResponse response;
        try {
            AlipayClient alipayClient = ZfbUtils.getRequest(this.config.getAppId(), this.config.getPriKey(), this.config.getPubAppCrtPath(), this.config.getPubAliCrtPath(), this.config.getPubRootCrtPath());
            AlipayFundTransUniTransferRequest request = new AlipayFundTransUniTransferRequest();
            request.setBizContent(JSON.toJSONString(content));
            response = (AlipayFundTransUniTransferResponse)alipayClient.certificateExecute(request);
        } catch (ThirdException ex) {
            throw ex;
        } catch (AlipayApiException ex1) {
            ex1.printStackTrace();
            throw new ThirdException(ThirdStatus.ZFB);
        }

        if (!response.isSuccess()) {
            throw new ThirdException(ThirdStatus.ZFB);
        }
    }
}

